//
//  RequestTool.m
//  HomeDelivery
//
//  Created by apple on 16/7/21.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "RequestTool.h"
 #define YYEncode(str) [str dataUsingEncoding:NSUTF8StringEncoding]
@implementation RequestTool
+(void)requestDataWithType:(NSString *)type andUrlString:(NSString *)urlString andParameters:(NSDictionary *)dict andFinishedWith:(void(^)(id response,NSError *error))block
{
    NSString *String=nil;
    if ([urlString hasPrefix:@"http"]) {
        String=[urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<> "].invertedSet];
   
    }else
    {
        String=[[NSString stringWithFormat:@"%@/%@",URL,urlString] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<> "].invertedSet];
    }
    
    //增加这几行代码；
    AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
    [securityPolicy setAllowInvalidCertificates:YES];
    
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
    [manager setSecurityPolicy:securityPolicy];
    // 设置超时时间
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 20.f;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/plain", @"text/javascript", @"text/json", @"text/html", nil];
    
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    if ([type isEqualToString:@"post"]) {
        [manager POST:String parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            block(responseObject,nil);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            block(nil,error);
        }];
    }else
    {
        [manager GET:String parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            block(responseObject,nil);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            block(nil,error);
        }];
    }

}
+(void)uploadImageURLString:(NSString *)urlString WithDict:(NSDictionary *)dict andNSData:(NSData *)imageData andBlock:(void(^)(id data,NSError *error))block
{
    NSString *String=nil;
    if ([urlString hasPrefix:@"http"]) {
        String=[urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<> "].invertedSet];
    }else
    {
       String=[[NSString stringWithFormat:@"%@/%@",URL,urlString] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<> "].invertedSet];
    }
    //增加这几行代码；
    AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
    [securityPolicy setAllowInvalidCertificates:YES];
    
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
    [manager setSecurityPolicy:securityPolicy];
    // 设置超时时间
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 20.f;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/plain", @"text/javascript", @"text/json", @"text/html", nil];
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
         NSData *paraData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
        //添加图片流到字节流后面
    
    
    
    NSInteger length=paraData.length;
    NSString *str=[NSString stringWithFormat:@"%zd",length];
    NSData *data =[str dataUsingEncoding:NSUTF8StringEncoding];
   
    NSMutableData *requestData=[NSMutableData dataWithBytes:data.bytes length:data.length];
    [requestData appendData:paraData];
    [requestData appendData:imageData];
    
//    [manager POST:String parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData)
//    {
//         [formData appendPartWithFormData:requestData name:@"ImageContext"];
//    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
//    {
//        NSLog(@"success--%@",[responseObject[@"ReturnObject"]stringByRemovingPercentEncoding]);
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        NSLog(@"error--%@",error.description);
//
//    }];
   
    
    

//    //json字节流
//     NSData *paraData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
//    //添加图片流到字节流后面
//     NSMutableData * requestData = [NSMutableData dataWithData:paraData];
//     [requestData appendData:imageData];
//    
//    [manager uploadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:String]] fromData:requestData progress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
//        NSLog(@"response--%@",response);
//         NSLog(@"success--%@",[responseObject[@"ReturnObject"]stringByRemovingPercentEncoding]);
//        NSLog(@"error--%@",error);
//    }];
    
     [manager POST:String parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
         [formData appendPartWithFormData:requestData name:@"ImageContext"];
     //[formData appendPartWithInputStream:[[NSInputStream alloc]initWithData:requestData] name:@"ImageContext" fileName:@"ImageContext" length:requestData.length mimeType:@"image/jpeg"];
     } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
          NSLog(@"success--%@",[responseObject[@"ReturnObject"]stringByRemovingPercentEncoding]);
         block(responseObject,nil);
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         NSLog(@"error--%@",error.description);
         block(nil,error);

     }];

    
}
@end
